<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/6/30
 * Time: 13:21
 */

namespace ElementVip\JwOms\Services;

use Carbon\Carbon;
use ElementVip\Component\Order\Models\Order;
use ElementVip\Component\Order\Models\OrderItem;
use ElementVip\Component\Product\Models\Product;
use ElementVip\Component\Refund\Models\RefundLog;
use ElementVip\JwOms\Models\OmsSyncLog;
use ElementVip\JwOms\Models\OmsUploadLog;
use ElementVip\Component\Refund\Models\Refund;
use ElementVip\Component\Brand\Models\Brand;

class RefundService
{
    protected $uploadLog;

    public function __construct()
    {
        $this->uploadLog = new OmsUploadLog();
    }

    /**
     * 获取未发货的订单售后的取消订单发货数据
     */
    public function getCancelOrderRefundData()
    {
        $tag = $this->uploadLog->getLastTag('OrderCancel');
        $data = '';

        $refunds = Refund::where('type', 1)
            ->where('status', 8)
            ->where('updated_at', '>', $tag)
            ->get();
        $lastTag = Carbon::now();

        if (count($refunds) > 0) {
            /*$grouped = $refunds->groupBy('order_id');
            foreach ($grouped as $key => $item) {
                $order = Order::find($key);

                if ($order AND $order->distribution_status == 0 AND $order->status == Order::STATUS_CANCEL)    //如果订单未发货
                {
                    $head = 'RCDCANCELNEW';
                    $order_no = $order->order_no;
                    $warehouse = '';
                    $company = 'JW';  //品牌名称
                    $data = $data . $head . ';' . $order_no . ';' . $warehouse . ';' . $company . "\r";
                }
            }*/

            foreach ($refunds as $key => $item) {
                $order = Order::find($item->order_id);
                if ($order AND $order->distribution_status == 0) {
                    $head = 'RCDCANCELNEW';
                    $order_no = $order->order_no;
                    $sku = '';  //如果订单已取消，此字段传空
                    $num = '';  //如果订单已取消，此字段传空
                    $warehouse = '';
                    $company = 'JW';  //品牌名称

                    if ($order->status != Order::STATUS_CANCEL) //如果订单未取消
                    {
                        $model = $item->orderItem->getModel();
                        $sku = $model->sku ? $model->sku : '';
                        $num = $item->quantity;
                    }
                    $data = $data . $head . ';' . $order_no . ';' . $sku . ';' . $num . ';' . $warehouse . ';' . $company . "\r";
                }
            }
        }

        return ['data' => $data, 'lastTag' => $lastTag];
    }


    /**
     * 获取退货数据
     * @return array
     */
    public function getRefundData()
    {
        $tag = $this->uploadLog->getLastTag('OrderReturn');
        $data = '';

        /*$refunds = Refund::where('type', 1)*/
        $refunds = Refund::where('type', 4)
            ->where('status', 5)
            ->where('updated_at', '>', $tag)
            ->get();
        $lastTag = Carbon::now();

        if (count($refunds) > 0) {
            foreach ($refunds as $key => $item) {
                $order = Order::find($item->order_id);
                $orderItem = OrderItem::find($item->order_item_id);
                $address = explode(' ', $order->address_name);

                $data_head = 'RCHDRRTNEW';
                $warehouse = '';
                $return_no = $item->refund_no;
                $company = 'JW';
                $buyer_nick = $this->getUserName($order);
                $buyer_pay_money = (($orderItem->total / $orderItem->quantity) * $item->quantity) / 100;    //买家支付货款
                $buyer_pay_shipfee = $order->real_freight / 100;
                $ship_from = $order->accept_name;
                $ship_from_state = $address[0];
                $ship_from_city = $address[1];
                $ship_from_district = isset($address[2]) ? $address[2] : '';
                $ship_from_zipcode = '';
                $ship_address = $order->address; //详细地址
                /*$express_no = $item->shipping->shipping_tracking;// 退货的运单号
                $express_name = $this->ship($item->shipping->code);*/
                $ship_from_tel = '';
                $ship_from_mobile = $order->mobile;
                $tmall_no = $order->order_no;
                $return_type = '退货退款';
                $source_order_no = $order->order_no;

                $head = $data_head . ';' . $warehouse . ';' . $return_no . ';' . $company . ';' . $buyer_nick
                    . ';' . $buyer_pay_money . ';' . $buyer_pay_shipfee . ';' . $ship_from . ';' . $ship_from_state
                    . ';' . $ship_from_city . ';' . $ship_from_district . ';' . $ship_from_zipcode . ';' . $ship_address
                    /*. ';' . $express_no . ';' . $express_name . ';' . $ship_from_tel . ';' . $ship_from_mobile . ';' . $tmall_no*/
                    . ';' . $ship_from_tel . ';' . $ship_from_mobile . ';' . $tmall_no
                    . ';' . $return_type . ';' . $source_order_no . ';' . "\r";

                $model = $orderItem->getModel();
                if ($orderItem->type == 'ElementVip\Component\Product\Models\Product') {
                    /*$brand = Brand::find($model->goods->brand_id)->name;*/
                    $sku = $model->sku;
                } else {
                    /*$brand = Brand::find($model->brand_id)->name;*/
                    $sku = $model->goods_no;
                }
                $spc = explode(' ', $orderItem->item_meta['specs_text']);

                $s_data_head = 'RCDTLDNNEW';
                $s_return_no = $item->refund_no;
                $s_company = 'JW';
                $s_item = $sku;
                $s_upc_code = '';
                $s_goods_price = number_format($item->amount / $item->quantity / 100,2);
                $s_return_number = $item->quantity;
                $color = $spc[0];
                $size = $spc[1];
                $s_order_type = '退货退款';

                $s_item = $s_data_head . ';' . $s_return_no . ';' . $s_company . ';' . $s_item . ';' . $s_upc_code
                    . ';' . $s_goods_price . ';' . $s_return_number . ';' . $color . ';' . $size . ';' . $s_order_type . ';' . "\r";

                $data = $data . $head . $s_item;
            }
        }
        return ['data' => $data, 'lastTag' => $lastTag];
    }

    private function getUserName($item)
    {
        $name = '';
        if ($user = $item->user) {
            if ($user->nick_name) {
                $name = $user->nick_name;
            } elseif ($user->name) {
                $name = $user->nick_name;
            } else {
                $name = $user->mobile;
            }
        }
        return $name;
    }

    private function ship($code)
    {
        switch ($code) {
            case 'shunfeng':
                $ship = 'sf';
                break;
            case 'ems':
                $ship = 'ems';
                break;
            case 'shentong':
                $ship = 'sto';
                break;
            case 'yuantong':
                $ship = 'yto';
                break;
            case 'zhongtong':
                $ship = 'zto';
                break;
            case 'zhaijisong':
                $ship = 'zjs';
                break;
            case 'yunda':
                $ship = 'yunda';
                break;
            case 'huitongkuaidi':
                $ship = 'htky';
                break;
            case 'tiantian':
                $ship = 'ttkdex';
                break;
            case 'debangwuliu':
                $ship = 'dbl';
                break;
            default:
                $ship = 'sf';
        }
        return $ship;
    }

    /**
     * 同步退货数据
     * @param $file
     */
    public function syncRefund($file)
    {
        $fileUrl = '/storage/' . strstr($file, 'oms');
        $lines = file($file);
        $failed = [];
        $success = [];

        foreach ($lines as $key => $item) {
            $data = explode(';', $item);
            $head = $data[0];
            $refund_no = $data[1];
            $arrived_date_time = $data[4];
            $response_type = $data[6];    //approve退货成功，reject退货失败
            $response_note = $data[7];
            $order_no = $data[5];

            if (!$refund = Refund::where('refund_no', $refund_no)->first()) {
                //退货申请单不存在,记录日志
                $failed[] = '退货申请单 ' . $refund_no . ' 不存在';
                continue;
            }

            if ($head == 'RCHDRUP' AND $response_type == 'REJECT') {
                $failed[] = '退货申请单 ' . $refund_no . ' 退货失败：' . $response_note;
                RefundLog::create([
                    'refund_id' => $refund->id,
                    'user_id' => 0,
                    'admin_id' => 9999,
                    'action' => 'reject',
                    'note' => '退货失败',
                    'remark' => '退货失败:' . $response_note
                ]);
                continue;
            }

            if ($head == 'RCHDRUP' AND $response_type == 'APPROVE' AND $refund->status == 6) {
                //1.申请完成
                $refund->status = Refund::STATUS_SHOP_PAID;
                $refund->save();

                /*RefundLog::create([
                    'refund_id' => $refund->id,
                    'user_id' => 0,
                    'admin_id' => 1,
                    'action' => 'receipt',
                    'note' => '商城于 ' . $arrived_date_time . ' 收到退货，本次申请已完成',
                    'remark' => $response_note
                ]);*/
                RefundLog::create([
                    'refund_id' => $refund->id,
                    'user_id' => 0,
                    'admin_id' => 9999,
                    'action' => 'accept',
                    'note' => '商城于 ' . $arrived_date_time . ' 收到退货，等待退款',
                    'remark' => $response_note
                ]);

                //2.订单状态
                if ($order = Order::where('order_no', $order_no)->first()) {
                    if ($this->checkOrderRefund($order, $refund) AND $order->status != 6) {
                        $order->status = 6;
                        $order->save();

                        /*取消积分以及分销佣金*/
                        event('order.canceled', $order->id);
                        event('agent.order.canceled', $order->id);
                    } else {
                        event('order.refund.complete', $refund);
                        event('agent.order.refund', $refund);
                    }
                }

                $success[] = '退货申请单 ' . $refund_no . ' 退货成功';
            }
        }

        if (count($failed) > 0 OR count($success) > 0) {
            OmsSyncLog::create([
                'type' => 'OrderReturnShip',
                'file' => $fileUrl,
                'success_message' => $success,
                'failed_message' => $failed
            ]);
        }
    }

    /**
     * 判断订单里面的产品是否全部为完成退款申请
     * @param $object   order
     * @param $refund
     * @return bool
     */
    private function checkOrderRefund($object, $refund)
    {
        //已完成退款处理的产品
        $filtered = $object->refunds->filter(function ($item) use ($refund) {
            return $item->id !== $refund->id AND ($item->status == 3 OR $item->status == 8);
        });

        //除开当前处理的退换货，订单中的其他产品
        $filtered2 = $object->items->filter(function ($item) use ($refund) {
            return $item->id !== $refund->order_item_id;
        });

        $num = $filtered->sum('quantity') + $refund->quantity;
        /*if (count($filtered) > 0) {
            $num = $filtered->sum('quantity') + $refund->quantity;
        }*/

        if ((count($filtered) == count($filtered2)) AND $num == $object->count) {
            return true;
        }

        return false;
    }
}